<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-06-18 09:35:42
 * @Description: 测站数据要素管理界面
-->
<template>
  <div class="station-type-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="测站类型编码">
          <el-select
            v-model="searchForm.stationTypeCode"
            placeholder="请选择测站类型编码"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in stationTypeOptions"
              :key="item.stationTypeCode"
              :label="item.stationTypeCode"
              :value="item.stationTypeCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测站类型名称">
          <el-select
            v-model="searchForm.stationTypeName"
            placeholder="请选择测站类型名称"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in stationTypeOptions"
              :key="item.stationTypeName"
              :label="item.stationTypeName"
              :value="item.stationTypeName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型编码">
          <el-input
            v-model="searchForm.dataTypeCode"
            placeholder="请输入数据类型编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="数据类型名称">
          <el-input
            v-model="searchForm.dataTypeName"
            placeholder="请输入数据类型名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd" :icon="Plus">
          新增测站类型
        </el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="!hasSelection"
          :icon="Delete"
        >
          批量删除
        </el-button>
        <el-button type="success" @click="handleImport" :icon="Upload">
          批量导入
        </el-button>
        <el-button type="info" @click="handleExport" :icon="Download">
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :height="view.height - 480"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="stationTypeCode"
          label="测站类型编码"
          width="150"
        />
        <el-table-column
          prop="stationTypeName"
          label="测站类型名称"
        />
        <el-table-column prop="dataTypeCode" label="数据类型编码" width="150" />
        <el-table-column prop="dataTypeName" label="数据类型名称" />
        <el-table-column
          prop="originalColumnName"
          label="原始数据列名"
        />
        <el-table-column
          prop="originalColumnNumber"
          label="原始数据列号"
          width="120"
        />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="测站类型编码" prop="stationTypeCode">
          <el-select
            v-model="formData.stationTypeCode"
            placeholder="请选择测站类型编码"
            filterable
            :disabled="isEdit"
            style="width: 100%"
            @change="handleStationTypeCodeChange"
          >
            <el-option
              v-for="item in stationTypeOptions"
              :key="item.stationTypeCode"
              :label="item.stationTypeCode"
              :value="item.stationTypeCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测站类型名称" prop="stationTypeName">
          <el-select
            v-model="formData.stationTypeName"
            placeholder="请选择测站类型名称"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in stationTypeOptions"
              :key="item.stationTypeName"
              :label="item.stationTypeName"
              :value="item.stationTypeName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型编码" prop="dataTypeCode">
          <el-input
            v-model="formData.dataTypeCode"
            placeholder="请输入数据类型编码"
          />
        </el-form-item>
        <el-form-item label="数据类型名称" prop="dataTypeName">
          <el-input
            v-model="formData.dataTypeName"
            placeholder="请输入数据类型名称"
          />
        </el-form-item>
        <el-form-item label="原始数据列名" prop="originalColumnName">
          <el-input
            v-model="formData.originalColumnName"
            placeholder="请输入原始数据列名"
          />
        </el-form-item>
        <el-form-item label="原始数据列号" prop="originalColumnNumber">
          <el-input-number
            v-model="formData.originalColumnNumber"
            placeholder="请输入原始数据列号"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入测站类型"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        accept=".xlsx,.xls,.csv"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 xlsx/xls/csv 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleImportSubmit"
            :loading="importLoading"
          >
            导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  onMounted,
  computed,
  watch,
} from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import axios from "axios";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Upload,
  Download,
  Edit,
  UploadFilled,
} from "@element-plus/icons-vue";
import apiConfig from "@/api/api";

// 类型定义
interface StationTypeItem {
  id: string;
  stationTypeCode: string;
  stationTypeName: string;
  dataTypeCode?: string;
  dataTypeName?: string;
  originalColumnName?: string;
  originalColumnNumber?: number;
  createdAt: string;
  updatedAt: string;
}

interface SearchForm {
  stationTypeCode?: string;
  stationTypeName?: string;
  dataTypeCode?: string;
  dataTypeName?: string;
}

interface FormData {
  stationTypeCode: string;
  stationTypeName: string;
  dataTypeCode?: string;
  dataTypeName?: string;
  originalColumnName?: string;
  originalColumnNumber?: number;
}

interface Pagination {
  pageNum: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const tableData = ref<StationTypeItem[]>([]);
const stationTypeOptions = ref<StationTypeItem[]>([]);
const tableLoading = ref(false);
const selectedRows = ref<StationTypeItem[]>([]);
const dialogVisible = ref(false);
const importDialogVisible = ref(false);
const isEdit = ref(false);
const submitLoading = ref(false);
const importLoading = ref(false);
const currentEditId = ref<string>("");

const searchForm = reactive<SearchForm>({
  stationTypeCode: "",
  stationTypeName: "",
  dataTypeCode: "",
  dataTypeName: "",
});

const pagination = reactive<Pagination>({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const formData = reactive<FormData>({
  stationTypeCode: "",
  stationTypeName: "",
  dataTypeCode: "",
  dataTypeName: "",
  originalColumnName: "",
  originalColumnNumber: undefined,
});

// 表单验证规则
const formRules = reactive({
  stationTypeCode: [
    { required: true, message: "请选择测站类型编码", trigger: "change" },
  ],
  stationTypeName: [
    { required: true, message: "请选择测站类型名称", trigger: "change" },
  ],
});

// 引用
const formRef = ref<FormInstance>();
const uploadRef = ref();

// 计算属性
const dialogTitle = computed(() =>
  isEdit.value ? "编辑测站类型" : "新增测站类型"
);
const hasSelection = computed(() => selectedRows.value.length > 0);

// API 调用方法封装
const stationTypeApi = {
  // 分页查询
  getPage: (params: any): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.getStationTypePage(
        params,
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 创建
  create: (data: any): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.createStationType(
        data,
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 更新
  update: (id: string, data: any): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.updateStationType(
        { ...data, id },
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 删除
  delete: (id: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.deleteStationType(
        { id },
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 批量删除
  batchDelete: (ids: string[]): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.batchDeleteStationTypes(
        { ids },
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 批量导入
  batchImport: (data: any): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.batchImportStationTypes(
        data,
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
  // 检查编码是否存在
  checkCode: (code: string, excludeId?: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      apiConfig.stationTypeManage.checkStationTypeCode(
        { code, excludeId },
        (response: any) => resolve({ data: response }),
        (error: any) => reject(error)
      );
    });
  },
};

// 生命周期
onMounted(() => {
  loadTableData();
  fetchStationTypeOptions();
});

// 加载测站类型选项
const fetchStationTypeOptions = async () => {
  try {
    const response = await axios.get('/algorithmApi/api1/station-type1/list');
    if (response.data.code === 200) {
      stationTypeOptions.value = response.data.data || [];
    } else {
      ElMessage.error(response.data.message || "获取测站类型选项失败");
    }
  } catch (error) {
    console.error("加载测站类型选项失败:", error);
    ElMessage.error("加载测站类型选项失败");
  }
};

// 加载表格数据
const loadTableData = async () => {
  try {
    tableLoading.value = true;
    const params = {
      ...searchForm,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    };

    const response = await stationTypeApi.getPage(params);
    if (response.data.data.code === 200) {
      const { list, total, pageNum, pageSize } = response.data.data.data;
      tableData.value = list || [];
      pagination.total = total || 0;
      pagination.pageNum = pageNum || 1;
      pagination.pageSize = pageSize || 10;
    } else {
      ElMessage.error(response.data.data.message || "获取数据失败");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    tableLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1;
  loadTableData();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    stationTypeCode: "",
    stationTypeName: "",
    dataTypeCode: "",
    dataTypeName: "",
  });
  pagination.pageNum = 1;
  loadTableData();
};

// 新增
const handleAdd = () => {
  isEdit.value = false;
  currentEditId.value = "";
  resetFormData();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row: StationTypeItem) => {
  isEdit.value = true;
  currentEditId.value = row.id;
  Object.assign(formData, {
    stationTypeCode: row.stationTypeCode,
    stationTypeName: row.stationTypeName,
    dataTypeCode: row.dataTypeCode || "",
    dataTypeName: row.dataTypeName || "",
    originalColumnName: row.originalColumnName || "",
    originalColumnNumber: row.originalColumnNumber,
  });
  dialogVisible.value = true;
};

// 删除单个
const handleDelete = async (row: StationTypeItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除测站类型"${row.stationTypeName}"吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await stationTypeApi.delete(row.id);
    if (response.data.code === 200) {
      ElMessage.success("删除成功");
      loadTableData();
    } else {
      ElMessage.error(response.data.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      "批量删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.value.map((row) => row.id);
    const response = await stationTypeApi.batchDelete(ids);
    if (response.data.code === 200) {
      ElMessage.success(`成功删除 ${response.data.data} 条记录`);
      selectedRows.value = [];
      loadTableData();
    } else {
      ElMessage.error(response.data.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 导入
const handleImport = () => {
  importDialogVisible.value = true;
};

// 导出
const handleExport = () => {
  // 这里可以实现导出功能
  ElMessage.info("导出功能开发中...");
};

// 表格选择变化
const handleSelectionChange = (selection: StationTypeItem[]) => {
  selectedRows.value = selection;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  loadTableData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page;
  loadTableData();
};

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false;
  resetFormData();
  formRef.value?.clearValidate();
};

// 测站类型编码变化时自动填充对应的名称
const handleStationTypeCodeChange = (value: string) => {
  const selectedType = stationTypeOptions.value.find(
    (item) => item.stationTypeCode === value
  );
  if (selectedType) {
    formData.stationTypeName = selectedType.stationTypeName;
  }
};

// 监听测站类型名称变化，自动填充对应的编码
watch(() => formData.stationTypeName, (newValue) => {
  if (newValue && !isEdit.value) {
    const selectedType = stationTypeOptions.value.find(
      (item) => item.stationTypeName === newValue
    );
    if (selectedType) {
      formData.stationTypeCode = selectedType.stationTypeCode;
    }
  }
});

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    // 检查编码是否重复
    if (!isEdit.value) {
      const checkResponse = await stationTypeApi.checkCode(
        formData.stationTypeCode,
        isEdit.value ? currentEditId.value : undefined
      );
      if (checkResponse.data.data) {
        ElMessage.error("测站类型编码已存在");
        return;
      }
    }

    submitLoading.value = true;
    let response;

    if (isEdit.value) {
      response = await stationTypeApi.update(currentEditId.value, formData);
    } else {
      response = await stationTypeApi.create(formData);
    }

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? "更新成功" : "创建成功");
      dialogVisible.value = false;
      loadTableData();
      
      // 如果是新增操作，刷新测站类型选项列表
      if (!isEdit.value) {
        fetchStationTypeOptions();
      }
    } else {
      ElMessage.error(response.data.message || "操作失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败");
  } finally {
    submitLoading.value = false;
  }
};

// 文件变化处理
const handleFileChange = (file: any) => {
  // 这里可以预处理文件
  console.log("选择的文件:", file);
};

// 导入提交
const handleImportSubmit = async () => {
  const files = uploadRef.value?.uploadFiles;
  if (!files || files.length === 0) {
    ElMessage.warning("请选择要导入的文件");
    return;
  }

  try {
    importLoading.value = true;
    // 这里需要解析文件内容，转换为对应的数据格式
    // 实际项目中可能需要使用 xlsx 库来解析 Excel 文件
    ElMessage.info("文件解析和导入功能需要根据具体需求实现");

    // 示例代码（需要根据实际情况调整）:
    // const formData = new FormData();
    // formData.append('file', files[0].raw);
    // 
    // const response = await axios.post('/api1/station-type1/batch/import', formData, {
    //   headers: {
    //     'Content-Type': 'multipart/form-data'
    //   }
    // });
    // 
    // if (response.data.code === 200) {
    //   ElMessage.success(`成功导入 ${response.data.data.successCount} 条记录`);
    //   importDialogVisible.value = false;
    //   loadTableData();
    //   fetchStationTypeOptions(); // 导入成功后刷新下拉选项
    // }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    importLoading.value = false;
  }
};

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    stationTypeCode: "",
    stationTypeName: "",
    dataTypeCode: "",
    dataTypeName: "",
    originalColumnName: "",
    originalColumnNumber: undefined,
  });
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN");
};


 // 视图高度
 const view = reactive({
    height: window.innerHeight,
  });
  window.onresize = function() {
    view.height = window.innerHeight;
  };
</script>

<style lang="scss" scoped>
.station-type-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
  }
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  .el-form-item {
    margin-bottom: 0;
  }
}

.operation-buttons {
  display: flex;
  gap: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload {
  width: 100%;
}

.el-table {
  .el-button + .el-button {
    margin-left: 8px;
  }
}
</style>
